#include <REGX52.H>
#include "LCD1602.h"
#include "intrins.h"

void LCD_Delay1ms(unsigned char time)		//@11.0592MHz
{
	unsigned char i, j;
	
	while(time--)
	{
		_nop_();
		i = 2;
		j = 199;
		do
		{
			while (--j);
		} while (--i);
	}
}

int LCD_Pow(int x,int y)
{
	unsigned char count;
	int re=1;
	for(count=0;count<y;count++)
	{
		re=re*x;
	}
	return re;
}

void LCD_WriteCommand(unsigned char command)//写入命令指令
{
	LCD_RS=0;
	LCD_RW=0;
	LCD_IO=command;//写入数据
	LCD_EN=1;
	_nop_();//延时2微秒
	LCD_EN=0;
	LCD_Delay1ms(2);
}
void LCD_WriteData(unsigned char Data)//写入数据指令
{
	LCD_RS=1;
	LCD_RW=0;
	LCD_IO=Data;//写入数据
	LCD_EN=1;
	_nop_();//延时2微秒
	LCD_EN=0;
	LCD_Delay1ms(2);//延时2毫秒
}
void LCD_Cursor(unsigned char line,unsigned char column)
{
	if(line==1)
	{
		LCD_WriteCommand(0x80|(column-1));//写入显示位置
	}
	else if(line==2)
	{
		LCD_WriteCommand(0x80|(64+column-1));//写入显示位置
	}
}

void LCD_Init()//LCD初始化操作
{
	LCD_WriteCommand(0x06);//模式设置指令（输入数据后光标右移，显示屏不移动）
	LCD_WriteCommand(0x0c);//显示开关控制指令（显示功能开，光标关）
	LCD_WriteCommand(0x38);//功能设定指令（8数据线，显示两行，5*7点阵）
	LCD_WriteCommand(0x01);//清屏操作
}

void LCD_ShowChar(unsigned char line,unsigned char column,unsigned char c)
{
	LCD_Cursor(line,column);
	LCD_WriteData(c);
}

void LCD_ShowString(unsigned char line,unsigned char column,unsigned char string[])
{
	unsigned char count=0;
	LCD_Cursor(line,column+count);//可以写外面的原因是，光标会自动移位
	for(count=0; string[count]!='\0';count++)
	{
		LCD_WriteData(string[count]);
	}
}

void LCD_ShowSignedNum(unsigned char line,unsigned char column,int c,unsigned char length)
{
	unsigned char count=0;
	int temp=0;
	int ret=0;
	LCD_Cursor(line,column);//可以写外面的原因是，光标会自动移位
	if(c<0)
	{
		c=-c;
		LCD_WriteData('-');
	}
	else if(c>=0)
	{
		LCD_WriteData('+');
	}
	ret=c;
	for(count=length-1; count>0; count--)
	{
		temp=ret/LCD_Pow(10,count-1);
		ret=ret%LCD_Pow(10,count-1);
		LCD_WriteData(temp+'0');
	}
}

void LCD_ShowNum(unsigned char line,unsigned char column,int c,unsigned char length)
{
	unsigned char count=0;
	int temp=0;
	int ret=0;
	LCD_Cursor(line,column);//可以写外面的原因是，光标会自动移位
	ret=c;
	for(count=length; count>0; count--)
	{
		temp=ret/LCD_Pow(10,count-1);
		ret=ret%LCD_Pow(10,count-1);
		LCD_WriteData(temp+'0');
	}
}

void LCD_ShowHexNum(unsigned char line,unsigned char column,int c,unsigned char length)
{
	unsigned char count=0;
	int temp=0;
	int ret=0;
	LCD_Cursor(line,column);//可以写外面的原因是，光标会自动移位
	ret=c;
	for(count=length; count>0; count--)
	{
		temp=ret/LCD_Pow(16,count-1);
		ret=ret%LCD_Pow(16,count-1);
		if(temp<10)
		{
			LCD_WriteData(temp+'0');
		}
		else if(temp>=10)
		{
			LCD_WriteData(temp+55);
		}
	}
}

void LCD_ShowBinNum(unsigned char line,unsigned char column,int c,unsigned char length)
{
	unsigned char count=0;
	int temp=0;
	int ret=0;
	LCD_Cursor(line,column);//可以写外面的原因是，光标会自动移位
	ret=c;
	for(count=length; count>0; count--)
	{
		temp=ret/LCD_Pow(2,count-1);
		ret=ret%LCD_Pow(2,count-1);
		LCD_WriteData(temp+'0');
	}
}